package com.twu.biblioteca.menu;

import com.twu.biblioteca.Book;
import com.twu.biblioteca.Index;
import com.twu.biblioteca.Reserver;
import com.twu.biblioteca.user.User;

import java.io.IOException;

public class BookListAuthorized extends BookList {
    private static final String PROMPT = "Enter a book ID to view details.";

    private final Reserver reserver;

    public BookListAuthorized(String title, User user, Index index, Reserver reserver, MenuInputReader reader)
    {
        super(title, user, index, reader);
        this.reserver = reserver;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(title + "\n");
        for(Book book : index.getBooks())
        {
            sb.append(book.toString() + "\n");
        }
        sb.append("\n" + PROMPT + "\n");
        return sb.toString();
    }

    @Override
    public void run()
    {
        try
        {
            int bookId = reader.readNumber();
            Book book = index.getBook(bookId);
            if(book != null)
            {
                showBookDetails(book);
            }
        }
        catch(InvalidOptionException e)
        {
            System.out.println(e.getMessage());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void showBookDetails(Book book)  {
        String title = Integer.toString(book.getItemId());
        BookDetails bookDetails = new BookDetails(title, user, reserver, reader, book);
        System.out.println(bookDetails.toString());
        bookDetails.run();
    }
}
